package com.project.lk.nurseapp.home.usermsg;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.SimpleViewSwitcher;
import com.lidong.photopicker.ImageCaptureManager;
import com.lidong.photopicker.PhotoPickerActivity;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.base.UrlContants;
import com.project.lk.nurseapp.db.UserDaoBean;
import com.project.lk.nurseapp.db.UserDaoBeanDao;
import com.project.lk.nurseapp.home.presenter.UserPresenter;
import com.project.lk.nurseapp.home.usermsg.presenter.IUpdateUserView;
import com.project.lk.nurseapp.home.usermsg.presenter.UserMsgPresenter;
import com.project.lk.nurseapp.login.model.UserBean;
import com.project.lk.nurseapp.utils.AddPhoto;
import com.project.lk.nurseapp.utils.ApkUtils;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.FileUtils;
import com.project.lk.nurseapp.utils.GlideCircleTransform;
import com.project.lk.nurseapp.utils.KeyboardUtils;
import com.project.lk.nurseapp.utils.PickerViewManager;
import com.project.lk.nurseapp.utils.ProgressUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class UserMsgActivity extends BaseActivity  implements IUpdateUserView{


    @BindView(R.id.user_icon)
    ImageView userIcon;
    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.user_phone)
    EditText userPhone;
    @BindView(R.id.user_sex)
    TextView userSex;
    @BindView(R.id.user_date)
    TextView userDate;
    @BindView(R.id.mProgressBar)
    SimpleViewSwitcher mProgressBar;
    private UserBean user;
    private UserMsgPresenter presenter;
    private String iconUrl;

    @Override
    protected void initData() {

        user = (UserBean) getIntent().getSerializableExtra("user");

        presenter = new UserMsgPresenter(this);
        ProgressUtils.setProgress(mProgressBar);
    }

    @Override
    protected void initView() {
        setTime();
    //用来回调照片不包括初始照片+
        mPicImageList = new ArrayList<>();
        showView();
    }
    //设置数据
    private void showView() {
        if (user!=null){
            Glide.with(this).load(user.getHeadImg())
                    .bitmapTransform(new GlideCircleTransform(this)).into(userIcon);
            userDate.setText(user.getBirth());
            userSex.setText(user.getSex());
            userName.setText(user.getNickName());
            userPhone.setText(user.getMobile());
            if (user.getMobile()==null) {
                user.setMobile("");
            }

            userName.setSelection(userName.getText().length());
            if (user.getNickName()==null){
                user.setNickName("");
            }
            if (user.getSex()==null){
                user.setSex("");
            }
            if (user.getBirth()==null){
                user.setBirth("");
            }
        }

    }
    //设置性别条目选择器
    public OptionsPickerView setSexView(){
        List list = new ArrayList<>();
        String []   name = new String[] { "男", "女"};
        for (int i = 0; i < name.length; i++) {
            list.add(name[i]);
        }
        return PickerViewManager.createOnePicker(list, this,userSex);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_msg;
    }

    private List<String> mPicImageList;
    @OnClick({R.id.back, R.id.user_icon_layout, R.id.user_name_layout, R.id.user_phone_layout, R.id.user_sex_layout, R.id.user_date_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (user!=null){  //数据为空直接退出
                    if (TextUtils.equals(user.getBirth(),userDate.getText().toString())
                            &&TextUtils.equals(user.getNickName(),userName.getText().toString())
                       &&TextUtils.equals(user.getMobile(),userPhone.getText().toString())
                            &&TextUtils.equals(user.getSex(),userSex.getText().toString())){  //没有修改信息直接退出
                        AppManager.getAppManager().finishActivity();
                    }else {  //修改了请求服务器修改信息
                        if (mProgressBar.getVisibility()==View.GONE) {
                            mProgressBar.setVisibility(View.VISIBLE);
                            presenter.updateUser(UrlContants.UPDATE_USERINFO_URL, userName.getText().toString()
                                    , userSex.getText().toString(), userDate.getText().toString(),userPhone.getText().toString());
                        }
                    }
                }else {
                    AppManager.getAppManager().finishActivity();
                }
                break;
            case R.id.user_icon_layout:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    if (ApkUtils.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)&&
                            ApkUtils.hasPermission(Manifest.permission.CAMERA)) {
                        AddPhoto.showPopupWindow(getLayoutId(), mPicImageList, this, 1);
                    }else {
                        ToastUtils.showShortToast("你禁止了相册和拍照的功能");
                    }
                }else {
                    AddPhoto.showPopupWindow(getLayoutId(), mPicImageList, this, 1);
                }
                break;
            case R.id.user_name_layout:

                break;
            case R.id.user_phone_layout:

                break;
            case R.id.user_sex_layout:
                KeyboardUtils.hideKeyboard(this);
                //设置性别条目选择器
                OptionsPickerView pickerSex = setSexView();
                pickerSex.show();
                break;
            case R.id.user_date_layout:
                KeyboardUtils.hideKeyboard(this);
                mTimePickerView.show();
                break;
        }
    }
    @Override
    public void onBackPressed() {  //提交信息到服务器
        if (user!=null){  //数据为空直接退出
            if (TextUtils.equals(user.getBirth(),userDate.getText().toString())
                    &&TextUtils.equals(user.getNickName(),userName.getText().toString())
                    &&TextUtils.equals(user.getMobile(),userPhone.getText().toString())
                    &&TextUtils.equals(user.getSex(),userSex.getText().toString())){  //没有修改信息直接退出
                AppManager.getAppManager().finishActivity();
            }else {  //修改了请求服务器修改信息
                if (mProgressBar.getVisibility()==View.GONE) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    presenter.updateUser(UrlContants.UPDATE_USERINFO_URL, userName.getText().toString()
                            , userSex.getText().toString(), userDate.getText().toString(),userPhone.getText().toString());
                }
            }

        }else {
            super.onBackPressed();
        }
    }
    private TimePickerView mTimePickerView;
    public void setTime() {
        //设置时间显示在文本上
        mTimePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Date newDate=new Date();

                if (newDate.getTime()<date.getTime()){
                    ToastUtils.showShortToast("选择的时间不合理");
                }else {
                    //设置时间显示在文本上
                    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd ", Locale.CHINA);
                    userDate.setText(format.format(date));
                }

            }
        }).setCancelColor(getResources().getColor(R.color.heard_background))
                .setSubmitColor(getResources().getColor(R.color.heard_background))
                .isCyclic(true)
                .setType(TimePickerView.Type.YEAR_MONTH_DAY).build();
    }

    private static final int CODE_RESULT_REQUEST = 4;

    private static final int REQUEST_CAMERA_CODE = 2;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择相册照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> stringArrayListExtra = intent.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    File albumFile = new File(stringArrayListExtra.get(0));
                    AddPhoto.cropRawPhoto(UserMsgActivity.this, Uri.fromFile(albumFile));

                    break;
                // 拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (AddPhoto.captureManager.getCurrentPhotoPath() != null) {
                        AddPhoto.captureManager.galleryAddPic();
                        // 照片地址
                        String imagePaht = AddPhoto.captureManager.getCurrentPhotoPath();

                        File file = new File(imagePaht);
                        AddPhoto.cropRawPhoto(UserMsgActivity.this, Uri.fromFile(file));
                    }
                    break;
                // 预览
                case CODE_RESULT_REQUEST:
                    if (intent != null) {
                        setImageToHeadView(intent);
                    }
                    break;

            }
            super.onActivityResult(requestCode, resultCode, intent);
        }
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    private void setImageToHeadView(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
            photo.compress(Bitmap.CompressFormat.PNG, 100, output);//把bitmap100%高质量压缩 到 output对象里

            byte[] iconByte = output.toByteArray();//转换成功了
            File file = new File(BaseApp.getContext().getExternalCacheDir() + "icon.png");

            String iconPath = FileUtils.saveBitmap(photo, file);
            //上传头像
            if (iconPath!=null) {
                presenter.postImg(UrlContants.POST_IMG_URL,iconPath);
            }
            Glide.with(this).load(iconByte).bitmapTransform(new GlideCircleTransform(this)).into(userIcon);

        }
    }


    @Override
    public void postImgSuccess() {

        if (presenter!=null) {
            if (presenter.getImgList()!=null&&presenter.getImgList().size()!=0) {
                Log.e("MLOG",presenter.getImgList().get(0).getUrl());
                iconUrl = presenter.getImgList().get(0).getUrl();
                presenter.postUserIcon(UrlContants.UPDATE_ICON_URL,presenter.getImgList().get(0).getUrl());
            }else {
                ToastUtils.showShortToast("修改头像失败");
            }

        }
    }

    @Override
    public void postImgFail() {

    }

    @Override
    public void updateIconSuccess() {
        if (iconUrl!=null) {  //把修改的头像插入本地数据库中
            UserDaoBeanDao userDaoBeanDao = BaseApp.getInstance().getDaoSession().getUserDaoBeanDao();
            UserDaoBean userDaoBean = UserInfoUtils.getUserInfoFromCache(String.valueOf(1));
            userDaoBean.setHeadImg(iconUrl);
            userDaoBeanDao.save(userDaoBean);
        }
    }

    @Override
    public void updateIconFail() {

    }

    @Override
    public void postUserMsgSuccess() {
        if (!TextUtils.isEmpty(userName.getText())) {  //把修改的昵称插入本地数据库中
            UserDaoBeanDao userDaoBeanDao = BaseApp.getInstance().getDaoSession().getUserDaoBeanDao();
            UserDaoBean userDaoBean = UserInfoUtils.getUserInfoFromCache(String.valueOf(1));
            userDaoBean.setNickName(userName.getText().toString());
            userDaoBeanDao.save(userDaoBean);
        }
        mProgressBar.setVisibility(View.GONE);
        AppManager.getAppManager().finishActivity();
    }

    @Override
    public void postUserMsgFail() {
        mProgressBar.setVisibility(View.GONE);
        AppManager.getAppManager().finishActivity();
    }
}
